#!/bin/bash

set -e
tools_path=/mnt/ilustre/app/medical/tools
data_path=/mnt/ilustre/app/medical/.data

script_path=${tools_path}/script

while getopts  "i:f:nc:p:m:q:" opts
do
        case  $opts  in
        i)
			interval=$OPTARG
			i=i
		;;
		f)
			interval=$OPTARG
			f=f
		;;
		n)
			cutadaptor=$OPTARG
			n=n
		;;
		c)
			cnv=$OPTARG
			c=c
		;;
		m)
			mem=$OPTARG
			m=m
		;;
		p)
			cpu=$OPTARG
			p=p
		;;
		q)
			query=$OPTARG
			q=q
		;;
		\?)
			echo "Usage: ana [-i brca44, brca12, brca12ph, luca50ph] [-f interval.bed] [-a 0|1] <path to reads file>"
            echo -e "\t-i intervals - luca50ph, brca12, brca12ph, brca44(default)"
            echo -e "\t-f gene list file, bed format, will override [-i] opt"
            echo -e "\t-a cut adaptor in the reads, 1(default)"
			echo -e "\t-------------------------"
			echo -e "\t-p qsub cpu used, 12(default)"
			echo -e "\t-m qsub memory used, 20(gb, default)"
            exit 1
		;;
        esac
done
shift $(($OPTIND - 1))

if [ -z "$1" ]; then
	echo "Usage: ana [-i brca44, brca12, brca12ph, luca50ph] [-f interval.bed] [-a 0|1] <path to reads file>"
	echo -e "\t-i intervals - luca50ph, brca12, brca12ph, brca44(default)"
	echo -e "\t-f gene list file, bed format, will override [-i] opt"
	echo -e "\t-a cut adaptor in the reads, 1(default)"
	echo -e "\t-------------------------"
	echo -e "\t-p qsub cpu used, 12(default)"
	echo -e "\t-m qsub memory used, 20(gb, default)"
	exit 1
fi



if [ -n "$i" ]; then
	ana_cmd="$ana_cmd -$i $interval"
fi

if [ -n "$f" ]; then
	ana_cmd="$ana_cmd -$f $interval"
fi

if [ -n "$n" ]; then
	ana_cmd="$ana_cmd -$n"
fi

if [ -n "$c" ]; then
	ana_cmd="$ana_cmd -$c $cnv"
fi


if [ -n "$p" ]; then
	qsub_cmd="$qsub_cmd -l nodes=1:ppn=$cpu"
fi

if [ -n "$m" ]; then
	qsub_cmd="$qsub_cmd -l mem=${mem}gb"
fi

if [ -n "$q" ]; then
	qsub_cmd="$qsub_cmd -$q $query"
fi

ana0=ana0;
ana=ana.pl
if [ "$interval" = "brca12ph" ]; then
	ana0603=ana0724.pl
else
	ana0603=ana_trim0703.pl
fi


ana1=.ana
error=.error
qsinfo=.qs
opt=.opt


time_rand=`date +%s%N`
echo $time_rand

perl ${script_path}/$ana $ana_cmd $1 $time_rand #2>$error

# if [ -s $error ]; then
	# exit 1;
# fi

# sample_name=`cat reads.list | awk 'NR==1{print $3}' |tr A-Z a-z`
sample_name=`cat $time_rand |tr A-Z a-z`

rm $time_rand



echo perl ${script_path}/$ana0603 $ana_cmd $1 | cat $script_path/$ana0 - > $ana1
chmod 750 $ana1

# echo $qsub_cmd

if [ -z "$qsub_cmd" ]; then
	qsub -N $sample_name $ana1 | tee $qsinfo
	echo -N $sample_name $ana1 > $opt
else
	qsub -N $sample_name $qsub_cmd $ana1 | tee $qsinfo
	echo -N $sample_name $qsub_cmd $ana1 > $opt
fi

rm $ana1

qsid=`cat $qsinfo | awk -F "." '{print $1}'`

clear
echo a pbs job, id $qsid, named $sample_name submitted...



# ${script_path}/iff.sh reads.list $qsid $sample_name &


exit 0

